import { BASE_URL } from '../../../http/config';

Page({
  data: {
    courseId: 0,
    userId: 0,
    content: '',
    contentLength: 0,
    selectedStar: 0,
    ratingDescriptions: ['很差', '较差', '一般', '不错', '很好'],
    isEdit: false // 是否编辑已有评价
  },

  onLoad(options) {
    const courseId = options.courseid;
    const userId = options.userid;
    console.log(courseId,userId);

    this.setData({
      courseId,
      userId
    });

    // 查询是否已评价（用于回显）
    wx.request({
      url: `${BASE_URL}/courseEvaluate/evaluate`,
      method: 'GET',
      data: {
        courseid: courseId,
        userid: userId
      },
      success: (res) => {
        console.log(res.data)
        if (res.data.code === 200 && res.data.data) {
          const evaluation = res.data.data;
          
          const contentText = evaluation.evaluateContent 
          this.setData({
            content: contentText,
            contentLength: contentText.length,
            selectedStar: evaluation.score ,
           isEdit: true
          });
        }else {
          this.setData({
            isEdit: false  // 没有评价过
          });
        }
      },
      
     
    });
  },

  onContentInput(e) {
    const content = e.detail.value;
    this.setData({
      content,
      contentLength: content.length
    });
  },

  onStarSelect(e) {
    const star = e.currentTarget.dataset.star;
    this.setData({
      selectedStar: star
    });
  },

  submitEvaluation() {
    const { content, selectedStar, courseId, userId, isEdit } = this.data;

    if (!content.trim()) {
      wx.showToast({
        title: '请输入评价内容',
        icon: 'none'
      });
      return;
    }

    if (selectedStar === 0) {
      wx.showToast({
        title: '请选择星级评分',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({ title: '提交中...' });

    wx.request({
      url: `${BASE_URL}/courseEvaluate`,
      method: isEdit ? 'PUT' : 'POST',
      header: { 'Content-Type': 'application/json' },
      data: {
        courseid: courseId,
        userid: userId,
        evaluateContent: content,  
        score: selectedStar
      },
      success: () => {
        wx.hideLoading();
        wx.showToast({
          title: isEdit ? '评价已更新' : '评价提交成功',
          icon: 'success',
          duration: 1500,
          success: () => {
            setTimeout(() => {
              wx.navigateBack();
            }, 1000);
          }
        });
      },
  
    });
  }
});
